package com.ruoyi.oss.factory;

import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.oss.enumd.OssEnumd;
import com.ruoyi.oss.exception.OssException;
import com.ruoyi.oss.service.IOssStrategy;
import com.ruoyi.oss.service.abstractd.AbstractOssStrategy;

import lombok.extern.slf4j.Slf4j;

/**
 * 文件上传Factory
 *
 * @author Lion Li
 */
@Slf4j
public class OssFactory {

	/**
	 * 初始化工厂
	 */
	public static void init() {
		log.info("初始化OSS工厂");
		String type = OssEnumd.MINIO.getValue();
		AbstractOssStrategy strategy = getStrategy(type);
		// 未初始化不处理
		if (strategy.isInit) {
			refresh(type);
			log.info("订阅刷新OSS配置 => " + type);
		}
	}

	/**
	 * 获取默认实例
	 */
	public static IOssStrategy instance() {
		String type = OssEnumd.MINIO.getValue();
		return instance(type);
	}

	/**
	 * 根据类型获取实例
	 */
	public static IOssStrategy instance(String type) {
		OssEnumd enumd = OssEnumd.find(type);
		if (enumd == null) {
			throw new OssException("文件存储服务类型无法找到!");
		}
		AbstractOssStrategy strategy = getStrategy(type);
		if (!strategy.isInit) {
			refresh(type);
		}
		return strategy;
	}

	private static void refresh(String type) {
		getStrategy(type).init();
	}

	private static AbstractOssStrategy getStrategy(String type) {
		OssEnumd enumd = OssEnumd.find(type);
		return (AbstractOssStrategy) SpringUtils.getBean(enumd.getBeanClass());
	}

}
